package com.epoint.utils.template.query;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.epoint.utils.JDBCUtil;
import com.epoint.utils.SQLUtil;

public class MySqlQueryById<T> extends QueryByIdTemplate<T>
{

    private Connection con = null;
    private ResultSet rs = null;
    private PreparedStatement ps = null;
    private T obj = null;

    @Override
    void getConnection() {
        con = JDBCUtil.getConnection();
    }

    /**
         * 执行sql返回结果
     * @param sql sql
     * @param id 组件id
     * @param clazz 要返回的class实例对象
     * @return 结果
     */
    @Override
    T queryData(String sql, String id, Class<T> clazz) {
        try {
            ps = con.prepareStatement(sql);
            ps.setString(1, id);
            System.out.println("queryData->" + ps);
            rs = ps.executeQuery();
            // while(rs.next()) 一定不能丢，否则报错!!!!!!!
            while(rs.next()) {
                obj = SQLUtil.queryObjectInfo(clazz, rs); 
            }
            
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("根据id查询对象信息模板错误！");
        }
        return obj;
    }

    @Override
    void closeConnection() {
        try {
            JDBCUtil.closeConnection(rs, ps, con);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("根据id查询对象信息模板连接关闭失败！");
        }
    }

    

}
